package com.md.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class GitOperationUtils {
  /**
   * 执行命令
   *
   * @param command 命令
   * @return 结果
   * @throws Exception
   */
  private static String executeGitCommand(final String command) throws Exception {
    // 创建命令
    ProcessBuilder builder = new ProcessBuilder();
    builder.command("sh", "-c", command);
    Process process = builder.start();

    // 读取命令输出
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    StringBuilder output = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      output.append(line).append("\n");
    }
    // 等待命令执行完成
    process.waitFor();
    return output.toString();
  }

  // 获取当前分支与指定分支之间的差异
  private static String getDiff(final String currentBranch, final String compareBranch) throws Exception {
    String command = "git diff " + compareBranch + "..." + currentBranch; // 获取当前分支与目标分支的差异
    return executeGitCommand(command);
  }


  private static String getCommitHash(final String ref) throws Exception {
    String command = "git rev-parse " + ref; // 使用 ref（如 HEAD 或 HEAD~1）来获取提交哈希
    return executeGitCommand(command);
  }

  public static void main(final String[] args) {
    // Git 仓库路径
    try {
      // 获取当前分支
      String currentBranch = getCurrentBranch();
      System.out.println("Current Branch: " + currentBranch);

      // 获取当前提交（本次提交）的哈希值
      String currentCommitHash = getCommitHash("HEAD");
      System.out.println("Current Commit Hash: " + currentCommitHash);

      // 获取上一个提交（上次提交）的哈希值
      String previousCommitHash = getCommitHash("HEAD~1");
      System.out.println("Previous Commit Hash: " + previousCommitHash);


      // 获取差异内容
//      String diff = getDiff(currentBranch, "origin/" + currentBranch); // 与 master 分支进行对比，您可以根据需要更改分支
      String diff = getDiff(currentCommitHash, previousCommitHash); // 与 master 分支进行对比，您可以根据需要更改分支
      System.out.println("Diff between " + currentBranch + " and master:");
      System.out.println(diff);


    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 获取当前 Git 仓库的分支
   *
   * @return 当前git仓库分支
   * @throws Exception
   */
  private static String getCurrentBranch() throws Exception {
    // Git 命令：获取当前分支
    String command = "git rev-parse --abbrev-ref HEAD";

    // 执行 Git 命令
    return executeGitCommand(command);
  }
}
